package com.lxy.controller;

import com.lxy.entity.AppInfo;
import com.lxy.entity.AppVersion;
import com.lxy.entity.DevUser;
import com.lxy.service.AppinfoService;
import com.lxy.service.VersionService;
import com.lxy.util.SessionUtils;
import com.lxy.vo.ResultVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class VersionController {
    @Autowired
    private VersionService versionService;
    @Autowired
    private AppinfoService appinfoService;
    @RequestMapping("/getVersion")
    public ResultVo getVersion(Long appid){
        List<AppVersion> list = versionService.getVersion(appid);

        return ResultVo.success(list);
    }

    @RequestMapping("/versionAdd")
    public ResultVo addOrUpdate(AppVersion appVersion, MultipartFile apkFile, HttpServletRequest request){
        String token = request.getHeader("token");
        if(apkFile!=null && !apkFile.isEmpty()){
            if(apkFile.getSize()>1024*1024) {
                return ResultVo.error("文件过大");
            }
            String originalFilename = apkFile.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if(extension.equalsIgnoreCase("apk")){
                String upload = request.getServletContext().getRealPath("upload");
                File path = new File(upload);
                if(!path.exists())path.mkdirs();

                String lastName =  UUID.randomUUID().toString().replace("-","")+"."+extension;
                try {
                    apkFile.transferTo(new File(upload+"/"+lastName));
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultVo.error("上传失败");
                }
                appVersion.setApkfilename(lastName);
            }else {
                return ResultVo.error("文件不是apk");
            }
        }
        DevUser devUser = (DevUser) SessionUtils.get(token);

        appVersion.setCreationdate(new Date());
        appVersion.setCreatedby(devUser.getId());
        versionService.add(appVersion);

        AppInfo appInfo = new AppInfo();
        appInfo.setId(appVersion.getAppid());
        appInfo.setVersionid(appVersion.getId());
        appinfoService.update(appInfo);

        return ResultVo.success(null);
    }
}
